/*
 * @lc app=leetcode.cn id=257 lang=javascript
 *
 * [257] 二叉树的所有路径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string[]}
 */
var binaryTreePaths = function (root) {
    if (!root) { return [] }
    let paths = []
    let nodeQ = [root]//BFS
    let pathQ=[root.val.toString()]//每次到达一个节点，记录到该节点的路径
    while(nodeQ.length){
        let node=nodeQ.shift()
        let path=pathQ.shift()//保证同步，记录路径和遍历节点同步
        if(!node.left&&!node.right){
            paths.push(path)//叶子节点，直接推入PATH，当前节点之前已经计算
        }else{
            if(node.left){
                nodeQ.push(node.left)
                pathQ.push(path+'->'+node.left.val)//有左节点，同步推入到达左节点的path
            }
            if(node.right){
                nodeQ.push(node.right)
                pathQ.push( path=path+'->'+node.right.val)//有右节点，同步推入到达右节点的path
            }
        }
    }
    return paths
};
// @lc code=end
root = { val: 1, right: { val: 2, left: { val: 2 }, right: { val: 5 } }, left: { val: 5 } }
binaryTreePaths(root)
var binaryTreePaths = function (root) {
    let res = []
    let dfs = function (root, s = "") {
        if (root) {
            if (root.left == null && root.right == null) {//叶子节点
                s = s + root.val
                res.push(s)
            } else {//非叶子节点
                s = s + root.val + '->'
                if (root.left) {
                    dfs(root.left, s)
                }
                if (root.right) {
                    dfs(root.right, s)
                }
            }
        }
    }
    dfs(root, "")
    return res
};//递归，将S作为参数可以一直随着深度改变而改变